/**
  ******************************************************************************
  * @file    timer1.c
  * @author  ashuai0110
  * @version V1.0
  * @date    2024-01-17
  * @brief   timer1驱动,适用于PIC16(L)F1788_9
  *
  ******************************************************************************
  * @attention
  *
  * Change Logs:
  * Date          Author        Notes
  * 2024-01-17    ashuai0110    完成基本内容
  *
  ******************************************************************************
  */

/* 包含头文件-----------------------------------------------------------------*/
#include "timer1.h"

/* 私有宏定义-----------------------------------------------------------------*/

/* 私有类型定义---------------------------------------------------------------*/

/* 私有变量-------------------------------------------------------------------*/

/* 全局变量-------------------------------------------------------------------*/

/* 私有函数原型---------------------------------------------------------------*/

/**
  * @brief  timer1初始化
  * @note   定时周期sec = 1/(Fosc/4/预分频/(0xFF-初值))
  * @param  value : timer0计数初值
  * @retval None
  */
void timer1_init(uint16_t value)
{
    T1CONbits.TMR1CS = 0; /* timer1时钟源选择位 0:Fosc/4  1:Fosc */
    T1CONbits.T1CKPS = 0; /* 预分频比 0:1 1:2 2:4 3:8 */
    
    TIMER1_SET_INITIAL_VAL(value);
    TMR1ON = 1;
    timer1_update_it_cmd(1);
}

/**
  * @brief  timer0取消初始化(恢复缺省)
  * @param  None
  * @retval None
  */
void timer1_de_init(void)
{
    T1CON = 0;
    T1GCON = 0;
    TMR1H = 0;
    TMR1L = 0;
    TMR1IF = 0;
    TMR1IE = 0;
}

/**
  * @brief  timer1溢出(更新)中断控制
  * @param  state : 0禁止中断 1允许中断
  * @retval None
  */
void timer1_update_it_cmd(uint8_t state)
{
    TMR1IF = 0; /* 清除timer1溢出位 0:未溢出 1:溢出 */
    TMR1IE = state; /* timer1溢出中断允许位 0:禁止中断 1:允许中断 */
}

void timer1_ccpx_init(uint8_t ccpx, uint16_t value)
{
    switch(ccpx)
    {
        case 1:
            CCP1CONbits.CCP1M = 0b1010;
            CCPR1H = value >> 8;
            CCPR1L = value & 0xFF;
            break;
        case 2:
            CCP2CONbits.CCP2M = 0b1010;
            CCPR2H = value >> 8;
            CCPR2L = value & 0xFF;
            break;
        case 3:
            CCP3CONbits.CCP3M = 0b1010;
            CCPR3H = value >> 8;
            CCPR3L = value & 0xFF;
            break;
    }
    
    timer1_ccpx_it_cmd(ccpx,1);
}

void timer1_ccpx_it_cmd(uint8_t ccpx, uint8_t state)
{
    switch(ccpx)
    {
        case 1:
            CCP1IF = 0;
            CCP1IE = state;
            break;
        case 2:
            CCP2IF = 0;
            CCP2IE = state;
            break;
        case 3:
            CCP3IF = 0;
            CCP3IE = state;
            break;
    }
}


